﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Text.RegularExpressions;
using System.Web.Routing;
using System.Web.UI.WebControls;
using System.Web.Mvc;
using System.Web.UI;

namespace chapter3_2
{
    public class ShowRouteHandler : System.Web.Routing.IRouteHandler
    {
        static readonly Regex regex = new Regex(@"^\?routeinfo$", RegexOptions.IgnoreCase);
        #region IRouteHandler Members

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (regex.IsMatch(requestContext.HttpContext.Request.Url.Query))
            {
                OutputReouteTable(requestContext);
            }

            IRouteHandler handler = new MvcRouteHandler();
            return handler.GetHttpHandler(requestContext);
        }
        #endregion

        private void OutputReouteTable(RequestContext requestContext)
        {
            HttpResponseBase response = requestContext.HttpContext.Response;
            System.Web.Routing.RouteData data = requestContext.RouteData;

            Table table = new Table();

            foreach (Route route in RouteTable.Routes)
            {
                TableRow row = new TableRow();
                table.Rows.Add(row);
                TableCell cell = new TableCell();
                row.Cells.Add(cell);
                Label lbl = new Label();
                lbl.Text = route.Url;
                cell.Controls.Add(lbl);
                if (route.GetRouteData(requestContext.HttpContext) != null)
                {
                    lbl.ForeColor = System.Drawing.Color.Black;
                }
                else
                {
                    lbl.ForeColor = System.Drawing.Color.Gray;
                }
            }

            HtmlTextWriter writer = new HtmlTextWriter(response.Output);
            table.RenderControl(writer);

            response.End();
        }
    }
}